package com.example.design.a.singleton.deep;

/**
 * 并发下的单例模式
 */
public class Earth {

    private static boolean flag = false;

    private Earth() {
        synchronized (Earth.class) {
            if (!flag) {
                System.out.println(Thread.currentThread().getName() + ": OK");
                flag = true;
            } else {
                //                if (earth != null) {
                throw new RuntimeException("不要试图使用反射破坏单例");
                //                }
            }
        }
    }

    /**
     * 添加volatile关键词屏蔽指令重排
     */
    private volatile static Earth earth;

    /**
     * 双重检测锁模式
     * DCL(Double Check Lazy)懒汉式单例模式
     *
     * @return
     */
    public static Earth getInstance() {
        if (earth == null) {
            synchronized (Earth.class) {
                if (earth == null) {
                    earth = new Earth();
                }
            }
        }
        return earth;
    }
}
